package com.ruoyi.web.controller.basedata;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedata.domain.Concentrator;
import com.ruoyi.basedata.domain.vo.ConcentratorCommand;
import com.ruoyi.basedata.service.IConcentratorService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * 集中器管理Controller
 *
 * @author ruoyi
 * @date 2023-12-18
 */
@RestController
@RequestMapping("/basedata/concentrator")
public class ConcentratorController extends BaseController {


    @Autowired
    private IConcentratorService concentratorService;


    /**
     * 查询集中器管理列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:list')")
    @GetMapping("/list")
    public TableDataInfo list(Concentrator concentrator) {
        startPage();
        List<Concentrator> list = concentratorService.selectConcentratorList(concentrator);
        return getDataTable(list);
    }

    //查询所有集中器
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:list')")
    @GetMapping("/all")
    public TableDataInfo all(Concentrator concentrator) {
        List<Concentrator> list = concentratorService.selectConcentratorList(concentrator);
        return getDataTable(list);
    }

    /**
     * 导出集中器管理列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:export')")
    @Log(title = "集中器管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Concentrator concentrator) {
        List<Concentrator> list = concentratorService.selectConcentratorList(concentrator);
        ExcelUtil<Concentrator> util = new ExcelUtil<Concentrator>(Concentrator.class);
        util.exportExcel(response, list, "集中器管理数据");
    }

    /**
     * 获取集中器管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(concentratorService.selectConcentratorByID(id));
    }

    /**
     * 新增集中器管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:add')")
    @Log(title = "集中器管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Concentrator concentrator) {
        int flag = concentratorService.insertConcentrator(concentrator);
        if (flag > 0) {
            return toAjax(flag);
        } else {
            return AjaxResult.error("该集中器已存在");
        }

    }

    /**
     * 修改集中器管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:edit')")
    @Log(title = "集中器管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Concentrator concentrator) {
        return toAjax(concentratorService.updateConcentrator(concentrator));
    }

    /**
     * 删除集中器管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:remove')")
    @Log(title = "集中器管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable Long[] IDs) {
        List<String> list = concentratorService.deleteConcentratorByIDs(IDs);
        if (list.size() > 0) {
            return AjaxResult.error("已绑定设备档案，删除失败");
        } else {
            return AjaxResult.success("删除成功");
        }
    }


    //集中器命令下发
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:sendCommand')")
    @PostMapping("/sendCommand")
    public AjaxResult sendCommand(@RequestBody ConcentratorCommand concentratorCommand) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = concentratorService.sendCommand(concentratorCommand);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "系统异常，集中器命令下发失败");
        }
        return success(jsonObject);
    }


    //集中器命令下发后获取结果
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:sendCommand')")
    @PostMapping("/getCommandResult")
    public AjaxResult getCommandResult(@RequestBody ConcentratorCommand concentratorCommand) {
        JSONObject commandResult = null;
        try {
            commandResult = concentratorService.getCommandResult(concentratorCommand);
            return success(commandResult);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常，获取结果失败");
        }
    }

    @PostMapping("/exportTemplate")
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:exportTemplate')")
    public void exportTemplate(HttpServletResponse response){
        List<Concentrator> list = Collections.singletonList(new Concentrator());
        ExcelUtil<Concentrator> util = new ExcelUtil<>(Concentrator.class);
        util.exportExcel(response, list, "集中器管理数据");
    }

    @PostMapping("/importData")
    @PreAuthorize("@ss.hasPermi('basedata:concentrator:import')")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<Concentrator> util = new ExcelUtil<>(Concentrator.class);
            List<Concentrator> list = util.importExcel(file.getInputStream());
            concentratorService.importData(list);
            return success("导入成功");
        } catch (Exception e) {
            logger.error("导入失败", e);
            return error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('basedata:concentrator:edit')")
    @PostMapping("/bindTerminalsXb")
    public AjaxResult bindTerminalsXb(@RequestBody JSONObject object) {
        Long concentratorId = object.getLong("concentratorId");
        String protocolId = object.getString("protocolId");
        List<Long> terminalIds = object.getList("terminalIds", Long.class);
        return toAjax(concentratorService.bindTerminalsXb(concentratorId, protocolId, terminalIds));
    }

}
